package com.jxstyle.core.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.jxstyle.core.enums.UserStatusEnum;
import com.jxstyle.core.exception.BizException;
import com.jxstyle.core.exception.BizExceptionEnum;
import com.jxstyle.modular.entity.Menu;
import com.jxstyle.modular.service.UserService;

/**
 * 用户登录逻辑
 * 
 * @author weijx
 *
 */
@Service
public class UserDetailService implements org.springframework.security.core.userdetails.UserDetailsService {

	@Autowired
	private UserService userService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (username == null || "".equals(username)) {
			throw new BizException(BizExceptionEnum.LOGIN_PASSWORD_ERROR);
		}
		com.jxstyle.modular.entity.User user = userService.getByUsernameOrMobile(username);
		if (user == null) {
			throw new BizException(BizExceptionEnum.LOGIN_PASSWORD_ERROR);
		}
		if (user.getStatus().intValue() != UserStatusEnum.NORMAL.getValue()) {
			throw new BizException(BizExceptionEnum.LOGIN_STATUS_ERROR);
		}
		List<SimpleGrantedAuthority> authorities = this.authorities(user);

		try {
			return new SecurityUser(user,authorities);
		} catch (Exception e) {
			throw new BizException(BizExceptionEnum.LOGIN_PASSWORD_ERROR);
		}
	}

	private List<SimpleGrantedAuthority> authorities(com.jxstyle.modular.entity.User user) {

		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		List<Menu> menus = userService.getMenuListByUser(user);
		menus.forEach((menu) -> {
			authorities.add(new SimpleGrantedAuthority(menu.getUrl()));
		});
		return authorities;
	}
}
